package com.lingshu.customview;

import android.content.Context;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatSpinner;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/4/23 15:19
 * @Description
 */
public class CustomSpinner extends AppCompatSpinner {
    public boolean isDropDownMenuShown = false;

    /**
     * @param context 用来解决原生spinner点击同一选项无反应的问题
     */
    public CustomSpinner(Context context) {
        super(context);
    }

    public CustomSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = (position == getSelectedItemPosition());
        super.setSelection(position, animate);
        if (sameSelected) {
            getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
        }
    }

    //作用是在执行点击事件时，先设置一个标志位表示下拉菜单已经被显示过，然后再执行点击事件的相应操作
    @Override
    public boolean performClick() {
        this.isDropDownMenuShown = true;
        return super.performClick();
    }

    //调用super.setSelection(position)方法来设置Spinner选中的选项。这是非常重要的，因为只有通过调用父类的setSelection方法，才能将Spinner的选中状态更新为新的选项
    @Override
    public void setSelection(int position) {
        boolean sameSelected = (position == getSelectedItemPosition());
        super.setSelection(position);
        if (sameSelected) {
            getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
        }
    }
}
